from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QLabel, QPushButton, QSpinBox, QProgressBar, QTextEdit,
    QFileDialog, QMessageBox, QComboBox, QGroupBox, QFrame,
    QLineEdit, QTabWidget, QRadioButton, QStackedWidget
)
from PyQt6.QtCore import Qt, QSize, pyqtSlot, pyqtSignal
from PyQt6.QtGui import QColor, QFont, QPalette, QIcon

import os
import sys
from typing import Optional, List
import time

# 导入自定义模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ui.icon_manager import IconManager
from utils.config import ConfigManager
from utils.browser_worker import BrowserWorker


class MainWindow(QMainWindow):
    """主窗口类，管理用户界面和交互"""
    
    def __init__(self):
        """初始化主窗口"""
        super().__init__()
        
        # 初始化配置管理器
        self.config_manager = ConfigManager()
        
        # 初始化图标管理器
        self.icon_manager = IconManager()
        
        # 设置窗口属性
        self.setWindowTitle("Claude自动化交互工具")
        self.resize(800, 600)
        
        # 从配置恢复窗口位置和大小
        geometry = self.config_manager.get_window_geometry()
        if geometry and isinstance(geometry, dict):
            self.setGeometry(
                geometry.get("x", 100),
                geometry.get("y", 100),
                geometry.get("width", 800),
                geometry.get("height", 600)
            )
        
        # 初始化变量
        self.prompt_file_path = self.config_manager.get("last_prompt_file", "")
        self.note_content = None
        self.follow_up_prompts = self.config_manager.get("follow_up_prompts", [])
        self.worker = None
        
        # 设置样式表
        self._set_style()
        
        # 初始化UI
        self._init_ui()
        
        # 设置状态栏
        self.status_bar = self.statusBar()
        self.status_bar.showMessage("就绪")
        
        # 如果有保存的提示词文件路径，则更新UI
        if self.prompt_file_path:
            self._update_prompt_file_ui()
        
    def _set_style(self):
        """设置全局样式表"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f5f7;
            }
            QTabWidget::pane {
                border: 1px solid #ddd;
                border-radius: 8px;
                background-color: white;
                top: -1px;
            }
            QTabBar::tab {
                background-color: #f0f0f0;
                color: #666;
                border: 1px solid #ddd;
                border-bottom: none;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                padding: 8px 16px;
                min-width: 120px;
                font-weight: bold;
            }
            QTabBar::tab:selected {
                background-color: white;
                color: #4a86e8;
                border-bottom: 2px solid #4a86e8;
            }
            QTabBar::tab:hover:!selected {
                background-color: #e8e8e8;
            }
            QGroupBox {
                font-size: 14px;
                font-weight: bold;
                border: 1px solid #ddd;
                border-radius: 8px;
                margin-top: 16px;
                padding-top: 16px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top left;
                left: 10px;
                padding: 0 5px;
                color: #444;
                background-color: white;
            }
            QPushButton {
                background-color: #4a86e8;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-weight: bold;
                min-height: 30px;
                text-align: center;
                padding-left: 10px;
                padding-right: 10px;
            }
            QPushButton:hover {
                background-color: #3a76d8;
            }
            QPushButton:disabled {
                background-color: #aaa;
                color: #f0f0f0;
            }
            QPushButton#stop_button {
                background-color: #e8574a;
                color: white;
                min-width: 120px;
                margin: 0 5px;
                text-align: center;
            }
            QPushButton#stop_button:hover {
                background-color: #d8473a;
            }
            QPushButton#start_button {
                background-color: #4a86e8;
                color: white;
                min-width: 120px;
                margin: 0 5px;
                text-align: center;
            }
            QPushButton#start_button:hover {
                background-color: #3a76d8;
            }
            QPushButton#browse_button {
                background-color: #4a86e8;
                color: white;
                min-width: 80px;
            }
            QPushButton#save_button {
                background-color: #4a86e8;
                color: white;
                min-width: 100px;
            }
            QPushButton#delete_button {
                background-color: #e74c3c;
                color: white;
                min-width: 80px;
            }
            QPushButton#delete_button:hover {
                background-color: #c0392b;
            }
            QPushButton#delete_button:disabled {
                background-color: #aaa;
                color: #f0f0f0;
            }
            QComboBox {
                padding: 6px;
                border: 1px solid #ddd;
                border-radius: 4px;
                min-height: 30px;
            }
            QSpinBox {
                padding: 6px;
                border: 1px solid #ddd;
                border-radius: 4px;
                min-height: 30px;
            }
            QLabel {
                color: #444;
            }
            QRadioButton {
                min-height: 25px;
                font-size: 13px;
                padding: 2px;
            }
            QRadioButton::indicator {
                width: 15px;
                height: 15px;
            }
            QRadioButton::indicator:checked {
                border: 1px solid #4a86e8;
                background-color: #4a86e8;
                border-radius: 8px;
            }
            QRadioButton::indicator:unchecked {
                border: 1px solid #999;
                background-color: white;
                border-radius: 8px;
            }
            QRadioButton:checked {
                color: #4a86e8;
                font-weight: bold;
            }
            QProgressBar {
                border: 1px solid #ddd;
                border-radius: 4px;
                text-align: center;
                background-color: #f0f0f0;
                height: 20px;
            }
            QProgressBar::chunk {
                background-color: #4a86e8;
                border-radius: 3px;
            }
            QTextEdit {
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
                background-color: white;
                font-family: Arial, sans-serif;
            }
            QLineEdit {
                padding: 6px;
                border: 1px solid #ddd;
                border-radius: 4px;
                background-color: white;
                min-height: 30px;
            }
            QStackedWidget {
                border: none;
            }
        """)
        
    def _init_ui(self):
        """初始化UI组件"""
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(15, 15, 15, 15)
        
        # 创建标签页组件
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabPosition(QTabWidget.TabPosition.North)
        self.tab_widget.setDocumentMode(True)
        main_layout.addWidget(self.tab_widget)
        
        # 创建三个标签页
        self._create_browser_tab()
        self._create_note_generation_tab()
        self._create_note_preview_tab()
        
        # 添加任务状态区域
        self._create_task_status_area(main_layout)
        
        # 设置状态栏
        self.status_bar = self.statusBar()
        self.status_bar.setStyleSheet("background-color: #f0f0f0; color: #555;")
        self.status_bar.showMessage("就绪")
    
    def _create_task_status_area(self, parent_layout):
        """创建任务状态区域，包含进度条和状态标签"""
        status_frame = QFrame()
        status_frame.setFrameShape(QFrame.Shape.StyledPanel)
        status_frame.setStyleSheet("background-color: white; border: 1px solid #ddd; border-radius: 8px;")
        
        status_layout = QVBoxLayout(status_frame)
        status_layout.setSpacing(10)
        status_layout.setContentsMargins(15, 15, 15, 15)
        
        # 进度条布局
        progress_layout = QHBoxLayout()
        progress_label = QLabel("进度:")
        progress_label.setStyleSheet("font-weight: bold;")
        progress_layout.addWidget(progress_label)
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setFormat("%p%")
        progress_layout.addWidget(self.progress_bar)
        
        status_layout.addLayout(progress_layout)
        
        # 添加状态指示器
        indicators_layout = QHBoxLayout()
        
        # 状态指示区域
        status_indicators = QHBoxLayout()
        
        # 网站访问状态
        site_layout = QHBoxLayout()
        site_label = QLabel("网站访问状态:")
        site_label.setStyleSheet("font-weight: bold;")
        site_layout.addWidget(site_label)
        
        self.site_status_label = QLabel("未连接")
        self.site_status_label.setStyleSheet("color: #999; padding-left: 5px;")
        site_layout.addWidget(self.site_status_label)
        status_indicators.addLayout(site_layout)
        
        # 添加分隔符
        status_indicators.addSpacing(20)
        
        # Claude模型选择状态
        model_layout = QHBoxLayout()
        model_label = QLabel("Claude模型:")
        model_label.setStyleSheet("font-weight: bold;")
        model_layout.addWidget(model_label)
        
        self.model_status_label = QLabel("未选择")
        self.model_status_label.setStyleSheet("color: #999; padding-left: 5px;")
        model_layout.addWidget(self.model_status_label)
        status_indicators.addLayout(model_layout)
        
        # 添加状态指示区域到主布局
        indicators_layout.addLayout(status_indicators, 1)  # 将状态区域设为可拉伸
        
        # 操作按钮
        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(10)
        
        self.start_button = QPushButton("开始执行")
        self.start_button.setObjectName("start_button")
        self.start_button.setMinimumHeight(36)
        self.start_button.setMinimumWidth(120)  # 确保有足够宽度显示文本
        if self.icon_manager.font_id != -1:
            start_icon = self.icon_manager.get_icon("play-circle")
            if not start_icon.isNull():
                self.start_button.setIcon(start_icon)
                self.start_button.setIconSize(QSize(20, 20))
                # 确保显示图标和文本
                self.start_button.setStyleSheet("text-align: center; padding-left: 5px; color: white;")
        self.start_button.clicked.connect(self.start_automation)
        buttons_layout.addWidget(self.start_button)
        
        self.stop_button = QPushButton("停止执行")
        self.stop_button.setObjectName("stop_button")
        self.stop_button.setMinimumHeight(36)
        self.stop_button.setMinimumWidth(120)  # 确保有足够宽度显示文本
        if self.icon_manager.font_id != -1:
            stop_icon = self.icon_manager.get_icon("stop-circle")
            if not stop_icon.isNull():
                self.stop_button.setIcon(stop_icon)
                self.stop_button.setIconSize(QSize(20, 20))
                # 确保显示图标和文本
                self.stop_button.setStyleSheet("text-align: center; padding-left: 5px; color: white;")
        self.stop_button.clicked.connect(self.stop_automation)
        self.stop_button.setEnabled(False)
        buttons_layout.addWidget(self.stop_button)
        
        indicators_layout.addLayout(buttons_layout)
        status_layout.addLayout(indicators_layout)
        
        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.status_label.setStyleSheet("padding: 8px; background-color: #f9f9f9; border-radius: 4px; margin-top: 5px;")
        status_layout.addWidget(self.status_label)
        
        parent_layout.addWidget(status_frame)
    
    def _create_browser_tab(self):
        """创建浏览器自动化设置标签页"""
        browser_tab = QWidget()
        browser_layout = QVBoxLayout(browser_tab)
        browser_layout.setSpacing(15)
        browser_layout.setContentsMargins(15, 15, 15, 15)
        
        # 浏览器设置分组
        browser_group = QGroupBox("浏览器设置")
        browser_group.setStyleSheet("QGroupBox { font-weight: bold; }")
        browser_group_layout = QVBoxLayout(browser_group)
        browser_group_layout.setContentsMargins(10, 20, 10, 10)  # 增加顶部边距
        
        # 浏览器类型选择
        browser_type_layout = QHBoxLayout()
        browser_label = QLabel("浏览器类型:")
        browser_label.setStyleSheet("font-weight: normal;")
        browser_label.setFixedWidth(80)
        browser_type_layout.addWidget(browser_label)
        
        self.browser_combo = QComboBox()
        self._populate_browsers()
        self.browser_combo.setMinimumWidth(200)
        browser_type_layout.addWidget(self.browser_combo)
        browser_type_layout.addStretch()
        
        browser_group_layout.addLayout(browser_type_layout)
        browser_layout.addWidget(browser_group)
        
        # 添加说明区域
        info_frame = QFrame()
        info_frame.setStyleSheet("background-color: #f0f7ff; border-radius: 6px; padding: 10px;")
        info_layout = QVBoxLayout(info_frame)
        
        info_title = QLabel("浏览器自动化说明")
        info_title.setStyleSheet("font-weight: bold; font-size: 14px; color: #2c5aa0;")
        info_layout.addWidget(info_title)
        
        info_text = QLabel(
            "应用程序将通过自动控制浏览器访问 Claude AI 网站，执行以下操作：\n"
            "1. 自动打开浏览器并访问 Claude 网站\n"
            "2. 选择可用的 Claude 模型\n"
            "3. 根据提示词文件和交互设置进行多轮对话\n"
            "4. 收集对话内容并生成笔记\n\n"
            "请确保您的网络连接正常，并选择已安装的浏览器类型。"
        )
        info_text.setWordWrap(True)
        info_text.setStyleSheet("color: #444; line-height: 150%;")
        info_layout.addWidget(info_text)
        
        browser_layout.addWidget(info_frame)
        browser_layout.addStretch()
        
        # 添加到标签页
        self.tab_widget.addTab(browser_tab, "浏览器自动化设置")
    
    def _create_note_generation_tab(self):
        """创建笔记生成设置标签页"""
        note_gen_tab = QWidget()
        note_gen_layout = QVBoxLayout(note_gen_tab)
        note_gen_layout.setSpacing(15)
        note_gen_layout.setContentsMargins(15, 15, 15, 15)
        
        # 创建合并后的设置组框
        settings_group = QGroupBox("提示词与交互设置")
        settings_group.setStyleSheet("QGroupBox { font-weight: bold; }")
        settings_layout = QVBoxLayout(settings_group)
        settings_layout.setContentsMargins(10, 20, 10, 10)
        
        # 文件选择区域
        file_selector_layout = QHBoxLayout()
        
        file_label = QLabel("提示词文件:")
        file_label.setStyleSheet("font-weight: bold;")
        file_label.setFixedWidth(80)
        file_selector_layout.addWidget(file_label)
        
        self.file_path_label = QLabel("未选择文件")
        self.file_path_label.setStyleSheet("color: #999; background-color: #f9f9f9; padding: 5px; border-radius: 3px;")
        self.file_path_label.setMinimumHeight(30)
        file_selector_layout.addWidget(self.file_path_label, 1)
        
        self.browse_button = QPushButton("浏览...")
        self.browse_button.setObjectName("browse_button")
        self.browse_button.setFixedWidth(80)
        if self.icon_manager.font_id != -1:
            self.browse_button.setIcon(self.icon_manager.get_icon("folder-open"))
        self.browse_button.clicked.connect(self.browse_file)
        file_selector_layout.addWidget(self.browse_button)
        
        self.delete_button = QPushButton("删除")
        self.delete_button.setObjectName("delete_button")
        self.delete_button.setFixedWidth(80)
        if self.icon_manager.font_id != -1:
            delete_icon = self.icon_manager.get_icon("delete")
            if not delete_icon.isNull():
                self.delete_button.setIcon(delete_icon)
        self.delete_button.clicked.connect(self.delete_file)
        self.delete_button.setEnabled(False)  # 初始状态下禁用
        file_selector_layout.addWidget(self.delete_button)
        
        settings_layout.addLayout(file_selector_layout)
        
        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.Shape.HLine)
        separator.setFrameShadow(QFrame.Shadow.Sunken)
        separator.setStyleSheet("background-color: #ddd; margin: 10px 0;")
        settings_layout.addWidget(separator)
        
        # 交互次数设置
        count_layout = QHBoxLayout()
        count_label = QLabel("交互次数:")
        count_label.setStyleSheet("font-weight: bold;")
        count_label.setFixedWidth(80)
        count_layout.addWidget(count_label)
        
        self.iterations_spinbox = QSpinBox()
        self.iterations_spinbox.setRange(1, 10)
        self.iterations_spinbox.setValue(self.config_manager.get("iterations", 3))
        self.iterations_spinbox.setMinimumHeight(30)
        self.iterations_spinbox.setFixedWidth(80)
        self.iterations_spinbox.valueChanged.connect(self._update_follow_up_inputs)
        count_layout.addWidget(self.iterations_spinbox)
        count_layout.addStretch()
        
        settings_layout.addLayout(count_layout)
        
        # 使用标签页切换文件预览和多轮对话提示词
        content_tabs = QTabWidget()
        content_tabs.setDocumentMode(True)
        content_tabs.setStyleSheet("""
            QTabBar::tab {
                padding: 6px 10px;
                margin-right: 2px;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                background-color: #f0f0f0;
            }
            QTabBar::tab:selected {
                background-color: #4a86e8;
                color: white;
            }
            QTabBar::tab:hover:!selected {
                background-color: #e0e0e0;
            }
        """)
        
        # 文件预览标签页
        preview_tab = QWidget()
        preview_layout = QVBoxLayout(preview_tab)
        
        self.file_preview_text = QTextEdit()
        self.file_preview_text.setReadOnly(True)
        self.file_preview_text.setPlaceholderText("选择文件后将显示文件内容预览...")
        self.file_preview_text.setMinimumHeight(180)
        self.file_preview_text.setStyleSheet("border: 1px solid #ddd; border-radius: 4px; padding: 5px; font-family: monospace;")
        preview_layout.addWidget(self.file_preview_text)
        
        content_tabs.addTab(preview_tab, "文件预览")
        
        # 多轮对话提示词标签页
        prompts_tab = QWidget()
        prompts_layout = QVBoxLayout(prompts_tab)
        
        prompts_label = QLabel("设置每轮对话的提示词:")
        prompts_label.setStyleSheet("font-weight: normal; margin-bottom: 5px;")
        prompts_layout.addWidget(prompts_label)
        
        # 创建多轮对话提示词输入框容器
        self.follow_up_container = QWidget()
        self.follow_up_container_layout = QVBoxLayout(self.follow_up_container)
        self.follow_up_container_layout.setContentsMargins(0, 0, 0, 0)
        self.follow_up_container_layout.setSpacing(10)
        prompts_layout.addWidget(self.follow_up_container)
        
        # 初始化多轮对话提示词输入框
        self.follow_up_inputs = []
        self._create_follow_up_inputs()
        
        content_tabs.addTab(prompts_tab, "多轮对话提示词")
        
        # 将标签页添加到设置布局
        settings_layout.addWidget(content_tabs)
        
        # 将设置组添加到标签页布局
        note_gen_layout.addWidget(settings_group)
        note_gen_layout.addStretch()
        
        # 添加到标签页
        self.tab_widget.addTab(note_gen_tab, "笔记生成设置")
    
    def _create_note_preview_tab(self):
        """创建笔记预览与保存标签页"""
        preview_tab = QWidget()
        preview_layout = QVBoxLayout(preview_tab)
        preview_layout.setSpacing(15)
        preview_layout.setContentsMargins(15, 15, 15, 15)
        
        # 预览标题
        preview_label = QLabel("笔记预览")
        preview_label.setStyleSheet("font-weight: bold; font-size: 14px;")
        preview_layout.addWidget(preview_label)
        
        # 预览文本编辑框
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        self.result_text.setPlaceholderText("执行自动化后，生成的笔记将显示在这里...")
        self.result_text.setMinimumHeight(300)
        self.result_text.setStyleSheet("font-size: 13px; line-height: 1.5;")
        preview_layout.addWidget(self.result_text, 1)
        
        # 保存按钮
        save_layout = QHBoxLayout()
        save_layout.addStretch()
        
        self.save_button = QPushButton("保存笔记")
        self.save_button.setObjectName("save_button")
        if self.icon_manager.font_id != -1:
            self.save_button.setIcon(self.icon_manager.get_icon("save"))
        self.save_button.clicked.connect(self.save_note)
        self.save_button.setEnabled(False)
        self.save_button.setMinimumWidth(120)
        
        save_layout.addWidget(self.save_button)
        preview_layout.addLayout(save_layout)
        
        # 添加到标签页
        self.tab_widget.addTab(preview_tab, "笔记预览与保存")
    
    def _populate_browsers(self):
        """检测系统安装的浏览器并填充下拉框"""
        # 清空当前浏览器列表
        self.browser_combo.clear()
        
        # 检测已安装的浏览器
        installed_browsers = self._detect_installed_browsers()
        
        # 确保Chrome始终存在
        if "Chrome" not in installed_browsers:
            installed_browsers.insert(0, "Chrome")
        else:
            # 如果已安装Chrome，确保它在列表首位
            installed_browsers.remove("Chrome")
            installed_browsers.insert(0, "Chrome")
        
        # 填充下拉框
        for browser in installed_browsers:
            self.browser_combo.addItem(browser)
        
        # 从配置加载上次选择的浏览器
        last_browser = self.config_manager.get("browser_type", "Chrome")
        index = self.browser_combo.findText(last_browser, Qt.MatchFlag.MatchFixedString)
        if index >= 0:
            self.browser_combo.setCurrentIndex(index)
        
        # 连接信号以保存选择
        self.browser_combo.currentTextChanged.connect(self._save_browser_selection)
    
    def _detect_installed_browsers(self):
        """检测系统已安装的浏览器
        
        Returns:
            list: 已安装浏览器的列表
        """
        browsers = []
        
        # 检测Chrome
        chrome_paths = [
            # Windows路径
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
            # macOS路径
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            # Linux路径
            "/usr/bin/google-chrome",
            "/usr/bin/google-chrome-stable"
        ]
        
        for path in chrome_paths:
            if os.path.exists(path):
                browsers.append("Chrome")
                break
        
        # 检测Firefox
        firefox_paths = [
            # Windows路径
            "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
            "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
            # macOS路径
            "/Applications/Firefox.app/Contents/MacOS/firefox",
            # Linux路径
            "/usr/bin/firefox"
        ]
        
        for path in firefox_paths:
            if os.path.exists(path):
                browsers.append("Firefox")
                break
        
        # 检测Edge (仅Windows和macOS)
        edge_paths = [
            # Windows路径
            "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
            "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
            # macOS路径
            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
        ]
        
        for path in edge_paths:
            if os.path.exists(path):
                browsers.append("Edge")
                break
        
        # 检测Safari (仅macOS)
        if sys.platform == 'darwin' and os.path.exists("/Applications/Safari.app"):
            browsers.append("Safari")
        
        # 如果没有检测到任何浏览器，至少返回Chrome
        if not browsers:
            browsers.append("Chrome")
        
        return browsers
    
    def _save_browser_selection(self, browser_type):
        """保存浏览器选择到配置"""
        self.config_manager.set("browser_type", browser_type)
        self.config_manager.save_config()
    
    def _create_follow_up_inputs(self):
        """创建多轮对话提示词输入框"""
        # 清空容器中的所有控件
        for i in reversed(range(self.follow_up_container_layout.count())):
            item = self.follow_up_container_layout.itemAt(i)
            # 从布局中移除组件
            self.follow_up_container_layout.removeItem(item)
            # 如果是小部件，删除它
            if item.widget():
                item.widget().deleteLater()
            # 如果是布局，递归删除其中的组件
            elif item.layout():
                for j in reversed(range(item.layout().count())):
                    child = item.layout().itemAt(j)
                    if child.widget():
                        child.widget().deleteLater()
        
        # 清空输入框列表
        self.follow_up_inputs = []
        
        # 根据交互次数创建输入框
        max_inputs = min(self.iterations_spinbox.value(), 10) - 1  # 减1是因为第一轮使用文件提示词
        if max_inputs <= 0:
            return
            
        # 确保我们有足够的默认提示词
        while len(self.follow_up_prompts) < max_inputs:
            self.follow_up_prompts.append(f"请针对上一轮回答进行进一步的提问或深入探讨。")
        
        for i in range(max_inputs):
            input_layout = QHBoxLayout()
            
            # 轮次标签
            round_label = QLabel(f"第{i+2}轮:")
            round_label.setFixedWidth(50)
            input_layout.addWidget(round_label)
            
            # 提示词输入框
            prompt_input = QLineEdit()
            prompt_input.setText(self.follow_up_prompts[i] if i < len(self.follow_up_prompts) else "")
            prompt_input.setPlaceholderText("输入后续对话提示词")
            # 使用一个闭包来确保每个槽都有自己的索引值
            def create_slot(idx):
                return lambda text: self._save_follow_up_prompt(idx, text)
            prompt_input.textChanged.connect(create_slot(i))
            
            self.follow_up_inputs.append(prompt_input)
            input_layout.addWidget(prompt_input)
            
            self.follow_up_container_layout.addLayout(input_layout)
    
    def _update_follow_up_inputs(self):
        """更新多轮对话提示词输入框"""
        # 获取当前值并保存到配置
        iterations = self.iterations_spinbox.value()
        self.config_manager.set("iterations", iterations)
        self.config_manager.save_config()
        
        # 重新创建输入框
        self._create_follow_up_inputs()
    
    def _save_follow_up_prompt(self, index, text):
        """保存多轮对话提示词"""
        if index < len(self.follow_up_prompts):
            self.follow_up_prompts[index] = text
        else:
            self.follow_up_prompts.append(text)
        
        self.config_manager.set("follow_up_prompts", self.follow_up_prompts)
        self.config_manager.save_config()
    
    def browse_file(self):
        """打开文件选择对话框并预览文件内容"""
        file_dialog = QFileDialog()
        file_path, _ = file_dialog.getOpenFileName(
            self,
            "选择提示词文件",
            os.path.expanduser("~"),
            "文本文件 (*.txt);;Markdown文件 (*.md);;所有文件 (*.*)"
        )
        
        if file_path:
            self.prompt_file_path = file_path
            self.file_path_label.setText(os.path.basename(file_path))
            self.file_path_label.setStyleSheet("color: #333; background-color: #f0f7ff; padding: 5px; border-radius: 3px;")
            self.config_manager.set("last_prompt_file", file_path)
            self.config_manager.save_config()
            
            # 预览文件内容
            try:
                from utils.file_utils import read_prompt_file
                prompt_content = read_prompt_file(file_path)
                self.file_preview_text.setText(prompt_content)
            except Exception as e:
                self.file_preview_text.setText(f"无法预览文件内容: {str(e)}")
            
            # 启用删除按钮
            self.delete_button.setEnabled(True)
            
            # 自动切换到笔记生成设置标签页
            self.tab_widget.setCurrentIndex(1)
    
    def delete_file(self):
        """删除当前选择的提示词文件"""
        if not self.prompt_file_path:
            return
            
        # 确认删除
        reply = QMessageBox.question(
            self, 
            "确认删除", 
            f"确定要删除文件 '{os.path.basename(self.prompt_file_path)}' 吗？\n此操作不可恢复。",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            try:
                # 尝试删除文件
                os.remove(self.prompt_file_path)
                
                # 更新UI状态
                self.file_path_label.setText("未选择文件")
                self.file_path_label.setStyleSheet("color: #999; background-color: #f9f9f9; padding: 5px; border-radius: 3px;")
                self.file_preview_text.clear()
                self.file_preview_text.setPlaceholderText("选择文件后将显示文件内容预览...")
                
                # 清除路径并更新配置
                self.prompt_file_path = ""
                self.config_manager.set("last_prompt_file", "")
                self.config_manager.save_config()
                
                # 禁用删除按钮
                self.delete_button.setEnabled(False)
                
                QMessageBox.information(self, "成功", "文件已成功删除。")
            except Exception as e:
                QMessageBox.critical(self, "删除失败", f"无法删除文件: {str(e)}")
    
    def start_automation(self):
        """启动自动化流程"""
        # 检查是否选择了提示词文件
        if not self.prompt_file_path:
            QMessageBox.warning(self, "警告", "请先选择提示词文件！")
            # 切换到笔记生成设置标签页
            self.tab_widget.setCurrentIndex(1)
            return
        
        # 更新UI状态
        self.start_button.setEnabled(False)
        self.stop_button.setEnabled(True)
        self.browse_button.setEnabled(False)
        self.save_button.setEnabled(False)
        
        # 保存配置
        self.config_manager.set("iterations", self.iterations_spinbox.value())
        self.config_manager.save_config()
        
        # 启动BrowserWorker线程
        self.status_label.setText("自动化流程开始...")
        
        # 创建并启动工作线程
        browser_type = self.browser_combo.currentText()
        iterations = self.iterations_spinbox.value()
        
        # 获取follow_up_prompts
        follow_up_prompts = []
        for input_field in self.follow_up_inputs:
            follow_up_prompts.append(input_field.text())
        
        try:
            # 实例化并启动工作线程
            self.worker = BrowserWorker(
                self.prompt_file_path, 
                iterations, 
                browser_type, 
                follow_up_prompts
            )
            
            # 连接信号
            self.worker.progress_update.connect(self.update_progress)
            self.worker.status_update.connect(self.update_status)
            self.worker.finished.connect(self.on_finished)
            self.worker.error.connect(self.on_error)
            
            # 启动线程
            self.worker.start()
            
            # 更新UI
            self.site_status_label.setText("正在连接...")
            self.site_status_label.setStyleSheet("color: #f9a825; padding-left: 5px;")
            
            # 切换到预览标签页
            self.tab_widget.setCurrentIndex(2)
        except Exception as e:
            error_msg = f"启动工作线程失败: {str(e)}"
            print(error_msg)
            QMessageBox.critical(self, "错误", error_msg)
            # 恢复UI状态
            self.start_button.setEnabled(True)
            self.stop_button.setEnabled(False)
            self.browse_button.setEnabled(True)
    
    def stop_automation(self):
        """停止自动化流程"""
        # 停止BrowserWorker线程
        if hasattr(self, 'worker') and self.worker is not None:
            self.worker.stop()
            # 等待一段时间让线程有机会清理资源
            self.worker.wait(1000)  # 等待最多1秒
        
        # 更新UI状态
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)
        self.browse_button.setEnabled(True)
        
        self.status_label.setText("自动化流程已停止")
        self.site_status_label.setText("未连接")
        self.site_status_label.setStyleSheet("color: #999; padding-left: 5px;")
        self.model_status_label.setText("未选择")
        self.model_status_label.setStyleSheet("color: #999; padding-left: 5px;")
    
    def update_progress(self, value, message):
        """更新进度显示"""
        self.progress_bar.setValue(value)
        self.status_label.setText(message)
        
        # 更新状态栏
        self.status_bar.showMessage(message)
    
    def update_status(self, status_type, message):
        """更新状态显示
        
        Args:
            status_type: 状态类型 ('site'或'model')
            message: 状态消息
        """
        if status_type == "site":
            # 更新网站状态
            self.site_status_label.setText(message)
            if message == "已连接":
                self.site_status_label.setStyleSheet("color: #2e7d32; padding-left: 5px;")
            elif message == "正在连接":
                self.site_status_label.setStyleSheet("color: #f9a825; padding-left: 5px;")
            else:
                self.site_status_label.setStyleSheet("color: #999; padding-left: 5px;")
        elif status_type == "model":
            # 更新模型状态
            self.model_status_label.setText(message)
            if message == "已选择":
                self.model_status_label.setStyleSheet("color: #2e7d32; padding-left: 5px;")
            elif message == "正在选择":
                self.model_status_label.setStyleSheet("color: #f9a825; padding-left: 5px;")
            else:
                self.model_status_label.setStyleSheet("color: #999; padding-left: 5px;")
    
    def on_finished(self, note_content):
        """处理完成后的操作"""
        self.note_content = note_content
        self.result_text.setMarkdown(note_content)
        
        # 更新UI状态
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)
        self.browse_button.setEnabled(True)
        self.save_button.setEnabled(True)
        
        self.status_label.setText("自动化流程完成")
        self.update_progress(100, "自动化流程完成")
        
        # 更新状态标签样式
        self.status_label.setStyleSheet("padding: 5px; background-color: #e8f5e9; color: #2e7d32; border-radius: 3px; font-weight: bold;")
        self.site_status_label.setText("已连接")
        self.site_status_label.setStyleSheet("color: #2e7d32; padding-left: 5px;")
        self.model_status_label.setText("已选择")
        self.model_status_label.setStyleSheet("color: #2e7d32; padding-left: 5px;")
        
        # 切换到笔记预览标签页
        self.tab_widget.setCurrentIndex(2)
    
    def on_error(self, error_message):
        """错误处理"""
        QMessageBox.critical(self, "错误", error_message)
        
        # 更新UI状态
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)
        self.browse_button.setEnabled(True)
        
        self.status_label.setText(f"错误: {error_message}")
        self.status_label.setStyleSheet("padding: 5px; background-color: #ffebee; color: #c62828; border-radius: 3px;")
        self.site_status_label.setText("未连接")
        self.site_status_label.setStyleSheet("color: #999; padding-left: 5px;")
        self.model_status_label.setText("未选择")
        self.model_status_label.setStyleSheet("color: #999; padding-left: 5px;")
    
    def save_note(self):
        """保存笔记文件"""
        if not self.note_content:
            return
        
        # 打开保存对话框
        save_path, _ = QFileDialog.getSaveFileName(
            self,
            "保存笔记",
            os.path.join(
                self.config_manager.get("save_directory", os.path.expanduser("~/Documents")),
                f"Claude_Note_{os.path.basename(self.prompt_file_path).split('.')[0]}.md"
            ),
            "Markdown文件 (*.md);;文本文件 (*.txt);;所有文件 (*.*)"
        )
        
        if save_path:
            # 保存到所选路径
            try:
                with open(save_path, 'w', encoding='utf-8') as f:
                    f.write(self.note_content)
                
                # 更新配置
                self.config_manager.set("save_directory", os.path.dirname(save_path))
                self.config_manager.save_config()
                
                QMessageBox.information(self, "成功", "笔记已成功保存！")
            except Exception as e:
                QMessageBox.critical(self, "保存错误", f"保存笔记时出错: {str(e)}")
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 停止正在运行的工作线程
        if hasattr(self, 'worker') and self.worker is not None and self.worker.isRunning():
            self.worker.stop()
            self.worker.wait(1000)  # 等待最多1秒
            
        # 保存窗口位置和大小
        geometry = self.geometry()
        self.config_manager.update_window_geometry(
            geometry.x(),
            geometry.y(),
            geometry.width(),
            geometry.height()
        )
        
        # 保存其他配置，但不再保存use_direct_input和last_direct_prompt
        self.config_manager.set("browser_type", self.browser_combo.currentText())
        self.config_manager.set("iterations", self.iterations_spinbox.value())
        
        # 保存多轮对话提示词
        follow_up_prompts = []
        for input_field in self.follow_up_inputs:
            follow_up_prompts.append(input_field.text())
        self.config_manager.set("follow_up_prompts", follow_up_prompts)
        
        self.config_manager.save_config()
        
        # 正常关闭窗口
        event.accept()

    def _update_prompt_file_ui(self):
        """更新提示词文件相关UI"""
        if os.path.exists(self.prompt_file_path):
            # 更新文件路径标签
            self.file_path_label.setText(os.path.basename(self.prompt_file_path))
            self.file_path_label.setStyleSheet("color: #333; background-color: #f0f7ff; padding: 5px; border-radius: 3px;")
            
            # 启用删除按钮
            self.delete_button.setEnabled(True)
            
            # 预览文件内容
            try:
                from utils.file_utils import read_prompt_file
                prompt_content = read_prompt_file(self.prompt_file_path)
                self.file_preview_text.setText(prompt_content)
            except Exception as e:
                self.file_preview_text.setText(f"无法预览文件内容: {str(e)}")
        else:
            # 文件不存在，重置UI状态
            self.prompt_file_path = ""
            self.file_path_label.setText("未选择文件")
            self.file_path_label.setStyleSheet("color: #999; background-color: #f9f9f9; padding: 5px; border-radius: 3px;")
            self.delete_button.setEnabled(False)
            self.file_preview_text.clear() 